import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    SectionList, FlatList, Image, NativeModules, Alert,
} from 'react-native';
import TouchableItem from "react-navigation/src/views/TouchableItem";
import * as Color from "../../../lib.xjs/constant/Color";
import HttpHelper from "../../../lib.xjs/helper/HttpHelper";
import BizUser from "../../entity/BizUser";
import * as BizConstant from "../../constant/BizContant";
import {UUID} from "../../../lib.xjs/util/UUID";

const ic_phone = require('../../../../img/gaqu/ic_phone.png');

/** 仓体服务人员 */
export default class CabinSupportStuff extends Component {

    static navigationOptions = ({navigation}) => ({
        title: `${navigation.state.params.cabinName}-服务人员`,
    });

    mCabinId;

    constructor(props) {
        super(props);
        this.state = {
            /** 数据源 */
            mDatas: [],
        };
        this.mCabinId = this.props.navigation.state.params.cabinId;
    };

    componentDidMount(): void {
        this._getDatas1(this.mCabinId, true);
    };

    /** 每组 */
    _sectionComponent = (info) => {
        let personCount = info.section.users.length;
        return <View style={styles.group}>
            <View style={{flexDirection: 'row', alignItems: 'center',}}>
                <View style={{height: 16, width: 8, backgroundColor: Color.colorPrimaryLight, marginRight: 15,}}/>
                <Text style={styles.group_text}>{info.section.roleName}</Text>
            </View>
            <Text style={styles.group_text_right}>{personCount}人</Text>
        </View>
    };

    /** 每组的前后分隔View */
    _sectionSeparatorComponent = () => {
        return <View style={{height: 1, backgroundColor: Color.lightGray}}/>
    };

    /** 每项 */
    _itemComponent = (info) => {
        let name = info.item.realName;
        let number = info.item.username;
        return <View>
            <TouchableItem onPress={() => this._callSb(name, number)}>
                <View style={styles.item}>
                    <Text style={styles.item_text}>{name}</Text>
                    <View style={{flexDirection: 'row', alignItems: 'center',}}>
                        <Image style={styles.item_img} source={ic_phone} resizeMode={Image.resizeMode.cover}/>
                        <Text style={styles.item_text_number}>{number}</Text>
                    </View>
                </View>
            </TouchableItem>
        </View>
    };

    /** 每项之间的分隔View */
    _itemSeparatorComponent = () => {
        return <View style={{height: 0.5, backgroundColor: Color.lightGray, marginHorizontal: 5}}/>;
    };

    render() {
        return (
            <View style={{flex: 1}}>
                <SectionList
                    sections={this.state.mDatas}
                    keyExtractor={(item, index) => ("index" + index + item)}
                    stickySectionHeadersEnabled={true}

                    renderSectionHeader={(info) => this._sectionComponent(info)}
                    SectionSeparatorComponent={() => this._sectionSeparatorComponent()}

                    renderItem={(info) => this._itemComponent(info)}
                    ItemSeparatorComponent={() => this._itemSeparatorComponent()}

                    refreshing={false}
                    onRefresh={() => {
                        this._getDatas1(this.mCabinId, true)
                    }}
                />
                <HttpHelper ref={'http'}/>
            </View>
        );
    }

    /**
     * -----------------------------获取数据
     * 和 ListView 不同，它没有特殊的 DataSource 数据类型作为传入参数。
     * 它接收的仅仅只是一个 Array<object> 作为参数。
     * 参数数组中的每一项，需要包含 key 值作为唯一标示。数据结构如下：
     * [{title: 'Title Text', key: 'item1'}]
     */
    _getDatas1(cangId: string, isClear: boolean): void {
        if (!this.refs.http) return;
        let head = BizUser.getHeadParam(true);
        let body = new Map();
        body.set("cangId", cangId);

        this.refs.http.setURL(BizConstant.GET_CABIN_STUFF)
            .setMethod(HttpHelper.GET)
            .setNotiInfo("")
            .setHeadParams(head)
            .setBodyParams(body)
            .setRequestId(UUID.getOne())
            .setListener((responseCode: number, res: Object) => {
                if (responseCode !== HttpHelper.RESPONSE_SUCCESS) return;
                if (!res.data.roles.roles) return;

                // 初始化全局变量
                let datasInner = res.data.roles.roles;
                for (let roleItem of datasInner) {
                    roleItem.data = roleItem.users;     // 默认section的子列表是在data属性里面
                }

                if (!isClear) datasInner = [...this.state.mDatas, ...datasInner];
                this.setState({
                    mDatas: datasInner,
                });
            })
            .setTimeout(10 * 1000)
            .start(false);
    }

    _callSb = (name: string, phoneNumber: number) => {
        if (!NativeModules.NativeMethods || !phoneNumber) return;

        Alert.alert('提示', '联系[' + name + ']', [{
            text: '是', onPress: () => {
                NativeModules.NativeMethods.callSb(phoneNumber);
            }
        }, {
            text: '否', onPress: () => {
            }
        },
        ]);
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        flexDirection: 'column',
    },

    group: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: Color.lightGray,
        height: 30,
        paddingLeft: 15,
        paddingRight: 10,
    },

    group_text: {
        textAlign: 'center',
        textAlignVertical: 'center',
        color: Color.darkGray,
        fontSize: 16,
    },

    group_text_right: {
        textAlign: 'center',
        textAlignVertical: 'center',
        color: Color.darkGray,
        fontSize: 16,
    },

    item: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        backgroundColor: Color.windowWhite,
        height: 50,
        paddingLeft: 20,
        paddingRight: 10,
    },

    item_text: {
        textAlign: 'center',
        textAlignVertical: 'center',
        color: Color.black,
        fontSize: 18,
    },

    item_img: {
        height: 15,
        width: 15,
    },

    item_text_number: {
        textAlign: 'center',
        textAlignVertical: 'center',
        color: Color.darkGray,
        fontSize: 20,
    },
});
